import { Button, Form, Input, Result } from 'antd'
import React,{ useEffect } from 'react'
import { resetSignup, signup, SignupPlayload } from '../../store/actions/auth.action'
import Layout from './Layout'
import { useDispatch } from 'react-redux'
import { useSelector } from '../../hooks/useSelector'
import { Link } from 'react-router-dom'

const Signup = () => {
  // 获取dispatch
  const dispatch = useDispatch()
  const onFinish = (value: SignupPlayload)=> {
    dispatch(signup(value))
  }
  const auth = useSelector(state=> state.auth)

  const [form] = Form.useForm()
  // 1.注册成功清空表单
  useEffect(()=> {
    if(auth.signup.loaded&&auth.signup.success){
      form.resetFields()
    }
  },[auth])
  // 2.注册成功 显示成功的提示信息
  const showSucess = () => {
    if(auth.signup.loaded&&auth.signup.success){
      return <Result
      status="success"
      title="注册成功"
      extra={[
        <Button type="primary">
          <Link to={'/signin'}>登录</Link>
        </Button>
      ]}
    />
    }
  }
  // 3.注册失败 显示失败的提示信息
  const showError = () => {
    if(auth.signup.loaded&&!auth.signup.success){
      return <Result
      status="warning"
      title="注册失败"
      subTitle={auth.signup.message}
    />
    }
  }
  // 4.离开也买你之前 重置状态
  useEffect(()=>{
    return ()=> {
      dispatch(resetSignup())
    }
  },[])
  const signupForm = () => (
    <Form form={form} onFinish={onFinish}>
      <Form.Item name='name' label='昵称'>
        <Input/>
      </Form.Item>
      <Form.Item name='password' label='密码'>
        <Input.Password />
      </Form.Item>
      <Form.Item name='email' label='邮箱'>
        <Input />
      </Form.Item>
      <Form.Item name='email' label=''>
        <Button type='primary' htmlType='submit'>注册</Button>
      </Form.Item>
    </Form>
  )
  return (
    <Layout title='注册' subTitle='还没有账号？注册一个吧。'>
      {showSucess()}
      {showError()}
      {signupForm()}
    </Layout>
  )
}

export default Signup